package com.cn.mmd.controller;

import com.cn.mmd.model.*;
import com.cn.mmd.service.*;
import com.cn.mmd.tools.AliyunOssUtil;
import com.cn.mmd.tools.PictureUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 学生提问 问题
 * Created by Administrator on 2016/7/19 0019.
 */

@Controller
@RequestMapping(value = "page/issueStudent")
public class issueStudentController {

    @Autowired
    private IssueStudentService issueStudentService;

    @Autowired
    private StudentAppService studentAppService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentCourseService studentCourseService;

    @Autowired
    private TokenController tokenController;

    @Autowired
    private StudentCountController studentCountController;

    @Autowired
    private StudentCountService studentCountService;

    @Autowired
    private StudentIntegralController studentIntegralController;

    @Autowired
    private IssueAnswerService issueAnswerService;


    /**
     * 查看问题
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectIssue")
    @ResponseBody
    public synchronized Object selectIssue(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        Map<String, Object> map;
        Integer startrow = Integer.parseInt(request.getParameter("startrow"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        int type = Integer.parseInt(request.getParameter("type"));
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            if (startrow < 1) {
                startrow = 1;
            }
            startrow = (startrow - 1) * pageSize;
            Issue issue = new Issue();
            if (type == 1) {
                issue.setStartrow(startrow);
                issue.setPageSize(pageSize);
                issue.setIssuepersonid(studentId);
            } else {
                issue.setStartrow(startrow);
                issue.setPageSize(pageSize);
            }
            if (issueStudentService.selectAllByOd(issue) != null) {
                List<Issue> issueList = issueStudentService.selectAllByOd(issue);
                for (int i = 0; i < issueList.size(); i++) {
                    map = new HashMap<String, Object>();
                    issue = issueList.get(i);
                    map.put("issueId", issue.getIssueid() + "");
                    map.put("issueObject", issue.getIssueobject());
                    map.put("issuePersonId", issue.getIssuepersonid());
                    map.put("issueText", issue.getIssuetext());
                    map.put("issueTime", issue.getIssuetime());
//                    map.put("issueUrl",issue.getIssueurl());
                    List<Map> urlList = new ArrayList();
                    if (issue.getIssueurl() != null && !issue.getIssueurl().equals("")) {
                        String urls[] = issue.getIssueurl().split(",");
                        String url;
                        Map<String, Object> map1;
                        if (urls == null) {
                            map.put("issueUrl", urlList);
                        } else {
                            for (int i1 = 0; i1 < urls.length; i1++) {
                                if (!urls[i1].equals("")) {
                                    map1 = new HashMap<String, Object>();
                                    url = urls[i1];
                                    map1.put("url", url);
                                    urlList.add(map1);
                                }
                            }
                            map.put("issueUrl", urlList);
                        }
                    } else {
                        map.put("issueUrl", urlList);
                    }
                    studentApp = studentAppService.selectByPrimaryKey(issue.getIssuepersonid());
                    if (studentApp != null) {
                        map.put("issuePersonHeadPortrait", studentApp.getStudentheadportrait());
                        if (studentApp.getMynickname() != null && !studentApp.getMynickname().equals("")) {
                            map.put("issuePersonName", studentApp.getMynickname());
                        } else {
                            map.put("issuePersonName", studentApp.getStudentname());
                        }
                    } else {
                        map.put("issuePersonHeadPortrait", null);
                    }
                    mapList.add(map);
                }
                if (mapList.size() == issueList.size()&&mapList.size()>0) {
                    objectMap.put("data", mapList);
                    objectMap.put("code", 200);
                    objectMap.put("message", "成功");
                } else {
                    objectMap.put("code", 201);
                    objectMap.put("message", "数据获取失败");
                }
            } else {
                objectMap.put("code", 202);
                objectMap.put("message", "失败没有数据");
            }
        } else

        {
            objectMap.put("code", 203);
            objectMap.put("message", "此用户没有权限做此操作");
        }

        return objectMap;
    }


    @RequestMapping(value = "/selectIssueType")//查看问题类型
    @ResponseBody
    public synchronized Object selectIssueType(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        Map<String, Object> map;
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            Student student = studentService.selectByKey(studentId);
            if (student != null && student.getStudentclass() != null && !student.getStudentclass().equals("")) {
                Course course = new Course();
                course.setCourseclasss(student.getStudentclass());
                List<Course> courseList = studentCourseService.selectClasss(course);
                if (courseList != null) {
                    for (int i = 0; i < courseList.size(); i++) {
                        course = courseList.get(i);
                        map = new HashMap<String, Object>();
                        map.put("courseName", course.getCoursename());
                        map.put("courseId", course.getCourseid());
                        mapList.add(map);
                    }
                }

                if (mapList != null&&mapList.size()>0) {
                    objectMap.put("code", 200);
                    objectMap.put("message", "成功");
                    objectMap.put("data", mapList);
                } else {
                    objectMap.put("code", 201);
                    objectMap.put("message", "失败没有数据");
                }
            } else {
                objectMap.put("code", 202);
                objectMap.put("message", "失败没有这个学生");
            }
        } else {
            objectMap.put("code", 203);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }

    /**
     * 提问
     *
     * @param request
     * @param files
     * @return
     */
    @RequestMapping(value = "/addIssue")
    @ResponseBody
    public synchronized Object addIssue(HttpServletRequest request, @RequestParam(value = "files", required = false) MultipartFile[] files
    ) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String issueObject = request.getParameter("issueObject");
        String issueText = request.getParameter("issueText");
        String issuePersonId = request.getParameter("issuePersonId");
//        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm ");
        String token = request.getParameter("token");
        StudentApp studentApp;
//        System.out.println(issueObject);
        studentApp = (StudentApp) tokenController.token1(issuePersonId, token);
        if (studentApp != null) {
            if (issueText != null && !issueText.equals("")) {
                Date date = new Date();
                String issueTime = date.getTime() + "";
                String path = request.getSession().getServletContext().getRealPath("/") + "upload";
                Issue issue = new Issue();
                String issueUrl;
                File targetFile;
                if (files == null) {
                    issueUrl = "";
                } else {
                    issueUrl = "";
                    if (files.length <= 5) {
                        MultipartFile file;
                        String url;
                        for (int i = 0; i < files.length; i++) {
                            file = files[i];
                            if (!file.getOriginalFilename().equals("")) {
                                String key = issuePersonId + "-issue-" +file.getOriginalFilename() ;
                                targetFile = new File(path, key);
                                if (!targetFile.exists()) {
                                    targetFile.mkdirs();
                                    try {
                                        file.transferTo(targetFile);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    targetFile.delete();
                                    try {
                                        file.transferTo(targetFile);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                PictureUtil pictureUtil = new PictureUtil();
                                pictureUtil.zipWidthHeightImageFile(targetFile.getPath(), 720, 360, 4);
                                url = AliyunOssUtil.save(key, targetFile.getPath());
                                if (i < files.length - 1) {
                                    issueUrl = url + "," + issueUrl;
                                } else {
                                    issueUrl = issueUrl + url;
                                }
                                targetFile.delete();
                            }
                        }
                    } else {
                        objectMap.put("code", 202);
                        objectMap.put("message", "添加失败图片数量不对");
                        return objectMap;
                    }
                }
                issue.setIssueurl(issueUrl);
                issue.setIssuepersonid(issuePersonId);
                issue.setIssuetext(issueText);
                issue = issueStudentService.selectByUrl(issue);
                if (issue == null) {
                    issue = new Issue();
                    issue.setIssueobject(issueObject);
                    issue.setIssueurl(issueUrl);
                    issue.setIssuetext(issueText);
                    issue.setIssuepersonid(issuePersonId);
                    issue.setIssuetime(issueTime);
                    if (issueStudentService.insertSelective(issue) > 0) {
                        //保存
                        StudentCount studentCount = studentCountService.selectByPrimaryKey(issuePersonId);
                        StudentCount studentCount1 = new StudentCount();
                        if (studentCount != null) {
                            studentCount1.setIssueaddnum(studentCount.getIssueaddnum() + 1);
                            studentCount1.setStudentid(issuePersonId);
                            studentCountController.add(studentCount1, 1);
                        } else {
                            studentCount1.setIssueaddnum(1);
                            studentCount1.setStudentid(issuePersonId);
                            studentCountController.add(studentCount1, 0);
                        }
                        if (studentIntegralController.addIntegral(issuePersonId, "questions", 1) != null) {
                            objectMap.put("integral", "提问积分加+1");
                        } else {
                            objectMap.put("integral", "0");
                        }
                        objectMap.put("message", "成功");
                        objectMap.put("code", 200);
                    } else {
                        objectMap.put("message", "失败");
                        objectMap.put("code", 201);
                    }
                } else {
                    objectMap.put("message", "请勿重复添加");
                    objectMap.put("code", 202);
                }
            } else {
                objectMap.put("message", "内容不能为空");
                objectMap.put("code", 204);
            }
        } else {
            objectMap.put("code", 203);
            objectMap.put("message", "此用户没有权限做此操作");
        }

        return objectMap;
    }

    /**
     * 查看问题回答
     * 通过学生自己不能采纳自己的问题这个判断是在前端自己判断的
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectAnswerIssue")
    @ResponseBody
    public synchronized Object selectAnswerIssue(HttpServletRequest request) {
        Map<String, Object> objectMap1 = new HashMap<String, Object>();
        Map<String, Object> objectMap = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        Map<String, Object> map;
        Integer startrow = Integer.parseInt(request.getParameter("startrow"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        Integer issueId = Integer.parseInt(request.getParameter("issueId"));
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            if (startrow < 1) {
                startrow = 1;
            }
            startrow = (startrow - 1) * pageSize;
            Answer answer = new Answer();
            answer.setStartrow(startrow);
            answer.setPageSize(pageSize);
            answer.setIssueid(issueId);
            if (issueStudentService.selectByIssueIdOd(answer) != null) {
                List<Answer> answerList = issueStudentService.selectByIssueIdOd(answer);
                int a = 0;
                int n = 0;
                if (issueAnswerService.selectByPrimaryKey(issueId) != null) {
                    a = issueAnswerService.selectByPrimaryKey(issueId).getAnswerid();
                    n = 1;
                }
                for (int i = 0; i < answerList.size(); i++) {
                    answer = answerList.get(i);
                    map = new HashMap<String, Object>();
                    map.put("answerId", answer.getAnswerid() + "");
                    if (answer.getAnswerid() == a) {
                        map.put("answerType", 1);
                    }else {
                        map.put("answerType", 0);
                    }
                    map.put("answerPersonId", answer.getAnswerpersonid());
                    studentApp = studentAppService.selectByPrimaryKey(answer.getAnswerpersonid());
                    map.put("answerText", answer.getAnswertext());
                    map.put("answerTime", answer.getAnswertime());
                    map.put("answerUrl", answer.getAnswerurl());
                    if (studentApp.getMynickname() != null && !studentApp.getMynickname().equals("")) {
                        map.put("answerPersonName", studentApp.getMynickname());
                    } else {
                        map.put("answerPersonName", studentApp.getStudentname());
                    }
                    map.put("answerHeadPortrait", studentApp.getStudentheadportrait());
                    mapList.add(map);
                }
                if (mapList != null && mapList.size() == answerList.size()) {
                    answer = new Answer();
                    answer.setIssueid(issueId);
                    int num = issueStudentService.countNumByIssueId(answer);
                    Issue issue = issueStudentService.selectByPrimaryKey(issueId);
                    map = new HashMap<String, Object>();
                    map.put("issueId", issue.getIssueid() + "");
                    map.put("issueObject", issue.getIssueobject());
                    map.put("issuePersonId", issue.getIssuepersonid());
                    if (issue.getIssuepersonid().equals(studentId)) {
                        map.put("issueType", 1);//1表示是自己的可以去
                    } else {
                        map.put("issueType", 0);
                    }
                    map.put("issueText", issue.getIssuetext());
                    map.put("issueTime", issue.getIssuetime());
                    List<Map> urlList = new ArrayList();
                    if (issue.getIssueurl() != null && !issue.getIssueurl().equals("")) {
                        String urls[] = issue.getIssueurl().split(",");
                        String url;
                        Map<String, Object> map1;
                        if (urls == null) {
                            map.put("issueUrl", urlList);
                        } else {
                            for (int i1 = 0; i1 < urls.length; i1++) {
                                if (!urls[i1].equals("")) {
                                    map1 = new HashMap<String, Object>();
                                    url = urls[i1];
                                    map1.put("url", url);
                                    urlList.add(map1);
                                }
                            }
                            map.put("issueUrl", urlList);
                        }
                    } else {
                        map.put("issueUrl", urlList);
                    }
                    studentApp = studentAppService.selectByPrimaryKey(issue.getIssuepersonid());
                    if (studentApp != null) {
                        map.put("issuePersonHeadPortrait", studentApp.getStudentheadportrait());
                        if (studentApp.getMynickname() != null && !studentApp.getMynickname().equals("")) {
                            map.put("issuePersonName", studentApp.getMynickname());
                        } else {
                            map.put("issuePersonName", studentApp.getStudentname());
                        }
                    } else {
                        map.put("issuePersonHeadPortrait", "");
                    }
                    objectMap1.put("issue", map);
                    objectMap1.put("answer", mapList);
                    objectMap1.put("type",n);
                    objectMap.put("total", num);
                    objectMap.put("data", objectMap1);
                    objectMap.put("message", "成功");
                    objectMap.put("code", 200);
                } else {
                    objectMap.put("message", "数据获取失败");
                    objectMap.put("code", 201);
                }
            } else {
                objectMap.put("message", "暂无回答");
                objectMap.put("code", 202);
            }
        } else {
            objectMap.put("code", 203);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }

    /**
     * 回答问题
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/answerIssue")
    @ResponseBody
    public synchronized Object answerIssue(HttpServletRequest request) {// @RequestParam(value = "file", required = false) MultipartFile file
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String answerPersonId = request.getParameter("answerPersonId");
        String answerText = request.getParameter("answerText");
        Integer issueId = Integer.parseInt(request.getParameter("issueId"));
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(answerPersonId, token);
        if (studentApp != null) {
            if (answerText != null && !answerText.equals("")) {
                SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm ");
                Date date = new Date();
                String answerTime = time.format(date);
//        String path = request.getSession().getServletContext().getRealPath("/") + "upload";
                Answer answer;
                String answerUrl = "";
//        File targetFile;
//        if (file==null&&!file.getOriginalFilename().equals("")){
//            answerUrl="";
//        }else {
//            String key = answerPersonId + "-answer-" + file.getOriginalFilename();
//           targetFile = new File(path,key);
//            if (!targetFile.exists()) {
//                targetFile.mkdirs();
//                try {
//                    file.transferTo(targetFile);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            } else {
//                targetFile.delete();
//                try {
//                    file.transferTo(targetFile);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            answerUrl =AliyunOssUtil.save(key,targetFile.getPath());
//            targetFile.delete();
//        }
                answer = new Answer();
                answer.setAnswertext(answerText);
                answer.setAnswerurl(answerUrl);
                answer.setAnswerpersonid(answerPersonId);
                answer.setIssueid(issueId);
                answer = issueStudentService.selectByUrl(answer);
                if (answer == null) {
                    answer = new Answer();
                    answer.setAnswerurl(answerUrl);
                    answer.setIssueid(issueId);
                    answer.setAnswerpersonid(answerPersonId);
                    answer.setAnswertext(answerText);
                    answer.setAnswertime(answerTime);
                    if (issueStudentService.insertSelective(answer) > 0) {
                        StudentCount studentCount = studentCountService.selectByPrimaryKey(answerPersonId);
                        StudentCount studentCount1 = new StudentCount();
                        if (studentCount != null) {
                            studentCount1.setAnswerissuenum(studentCount.getAnswerissuenum() + 1);
                            studentCount1.setStudentid(answerPersonId);
                            studentCountController.add(studentCount1, 1);
                        } else {
                            studentCount1.setAnswerissuenum(1);
                            studentCount1.setStudentid(answerPersonId);
                            studentCountController.add(studentCount1, 0);
                        }
                        objectMap.put("code", 200);
                        objectMap.put("message", "成功");
                    } else {
                        objectMap.put("code", 201);
                        objectMap.put("message", "操作失败");
                    }
                } else {
                    objectMap.put("code", 202);
                    objectMap.put("message", "请勿发送重复消息");
                }
            } else {
                objectMap.put("code", 204);
                objectMap.put("message", "内容不能为空");
            }
        } else {
            objectMap.put("code", 203);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }

    /**
     * 采纳问题
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/addAnswerIssue")
    @ResponseBody
    public synchronized Object addAnswerIssue(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String studentId = request.getParameter("studentId");
        Integer issueId = Integer.parseInt(request.getParameter("issueId"));
        Integer answerId = Integer.parseInt(request.getParameter("answerId"));
        String answerPersonId = request.getParameter("answerPersonId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            Issue issue = issueStudentService.selectByPrimaryKey(issueId);
            if (issue.getIssuepersonid().equals(studentId)) {
                if (!issue.getIssuepersonid().equals(answerPersonId)) {
                    if (issueAnswerService.selectByPrimaryKey(issueId) == null) {
                        IssueAnswer issueAnswer = new IssueAnswer();
                        issueAnswer.setAnswerid(answerId);
                        issueAnswer.setIssueid(issueId);
                        if (issueAnswerService.insertSelective(issueAnswer) > 0) {
                            if (studentIntegralController.addIntegral(answerPersonId, "answer", 2) != null) {
                                objectMap.put("integral", "被采纳人积分加+2");
                            } else {
                                objectMap.put("integral", "0");
                            }
                            objectMap.put("code", 200);
                            objectMap.put("message", "采纳成功");
                        } else {
                            objectMap.put("code", 201);
                            objectMap.put("message", "采纳失败");
                        }
                    } else {
                        objectMap.put("code", 204);
                        objectMap.put("message", "这个问题已有采纳了。");
                    }
                } else {
                    objectMap.put("code", 205);
                    objectMap.put("message", "你不能采纳自己的回答");
                }
            } else {
                objectMap.put("code", 202);
                objectMap.put("message", "你没有权限操作这个问题");
            }
        } else {
            objectMap.put("code", 203);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }

}
